package cn.sdormitory.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.sdormitory.basedata.dao.BClassDao;
import cn.sdormitory.basedata.vo.BClassVo;
import cn.sdormitory.classHygiene.dao.AppClassHygieneDao;
import cn.sdormitory.classHygiene.dao.AppClassHygieneItemDao;
import cn.sdormitory.classHygiene.dao.ClassHygieneVoDao;
import cn.sdormitory.classHygiene.entity.AppClassHygiene;
import cn.sdormitory.classHygiene.entity.ClassHygieneItem;
import cn.sdormitory.classHygiene.req.ClassHygieneInfoReq;
import cn.sdormitory.classHygiene.vo.ClassHygieneVo;
import cn.sdormitory.common.utils.SysUserUtils;
import cn.sdormitory.service.AppClassroomHygieneService;
import cn.sdormitory.sys.dao.SysDeptDao;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sys.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className: AppClassroomHygieneServiceImpl
 * @author: Alex
 * @date: 2024/12/12
 **/
@Service
public class AppClassroomHygieneServiceImpl extends ServiceImpl<AppClassHygieneDao, AppClassHygiene> implements AppClassroomHygieneService {
	
	@Resource
	private AppClassHygieneDao appClassHygieneDao;
	
	@Resource
	private AppClassHygieneItemDao appClassHygieneItemDao;
	
	@Resource
	private ClassHygieneVoDao classHygieneVoDao;
	
	@Resource
	private SysUserDao sysUserDao;
	
	@Resource
	private SysUserRoleService sysUserRoleService;
	
	@Resource
	private SysDeptDao sysDeptDao;
	
	@Resource
	private BClassDao bClassDao;
	
	@Override
	public List<ClassHygieneVo> getTodayClassroomHygiene(String hygieneType, String checktime) {
		// hygieneType=0 日常班级卫生 1周末班级卫生
		
		Long userId = SysUserUtils.getSysUser().getId();
		// 先查出当前用户下的所有班级
		List<BClassVo> classList = getBClassVos(userId);
		List<Long> classIds = classList.stream().map(BClassVo::getClassId).collect(Collectors.toList());
		
		LambdaQueryWrapper<AppClassHygiene> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.in(AppClassHygiene::getClassId, classIds);
		lambdaQueryWrapper.and((wrapper) -> {
			wrapper.eq(AppClassHygiene::getTimeSlot, hygieneType).or().isNull(AppClassHygiene::getTimeSlot);
		});
		lambdaQueryWrapper.and((wrapper) -> {
			wrapper.apply("date_format(check_date,'%Y-%m-%d') = {0} or check_date is null", checktime);
		});
		List<AppClassHygiene> appClassHygienes = appClassHygieneDao.selectList(lambdaQueryWrapper);
		
		List<ClassHygieneVo> classHygieneVos = new ArrayList<>();
		for (BClassVo bClassVo : classList) {
			ClassHygieneVo classHygieneVo = new ClassHygieneVo();
			classHygieneVo.setClassId(bClassVo.getClassId());
			classHygieneVo.setClassName(bClassVo.getClassName());
			classHygieneVo.setClassTeacherName(bClassVo.getTeacherName());
			if (CollectionUtil.isNotEmpty(appClassHygienes)) {
				Optional<AppClassHygiene> any = appClassHygienes.stream().filter(appClassHygiene -> appClassHygiene.getClassId().equals(bClassVo.getClassId())).findAny();
				if (any.isPresent()) {
					AppClassHygiene appClassHygiene = any.get();
					classHygieneVo.setGrade(appClassHygiene.getGrade());
					classHygieneVo.setTimeSlot(String.valueOf(appClassHygiene.getTimeSlot()));
					classHygieneVo.setClassHygieneId(appClassHygiene.getId());
				}
			}
			classHygieneVos.add(classHygieneVo);
		}
		classHygieneVos.sort((p1, p2) -> {
			if (p1.getGrade() == null && p2.getGrade() == null) {
				return 0;
			}
			if (p1.getGrade() == null) {
				return -1;
			}
			if (p2.getGrade() == null) {
				return 1;
			}
			return p1.getGrade().compareTo(p2.getGrade());
		});
		
		return classHygieneVos;
	}
	
	@Override
	public AppClassHygiene getClassHygieneDetailById(String classHygieneId, String checkDate) {
		return appClassHygieneDao.selectClassHygieneWithItems(Long.parseLong(classHygieneId), checkDate);
	}
	
	@Override
	public int submitHygiene(ClassHygieneInfoReq hygieneInfoReq) {
		
		if (Objects.isNull(hygieneInfoReq.getId())) {
			// 新增
			AppClassHygiene appClassHygiene = new AppClassHygiene();
			appClassHygiene.setCheckDate(DateUtil.parse(hygieneInfoReq.getCheckDate()));
			appClassHygiene.setClassId(Long.parseLong(hygieneInfoReq.getClassId()));
			appClassHygiene.setCreateBy(SysUserUtils.getSysUser().getUsername());
			appClassHygiene.setNotes(hygieneInfoReq.getNotes());
			appClassHygiene.setGrade(hygieneInfoReq.getGrade());
			appClassHygiene.setTimeSlot(hygieneInfoReq.getTimeSlot());
			appClassHygiene.setCreateTime(new Date());
			String photos = String.join(",", hygieneInfoReq.getPhotos());
			appClassHygiene.setPhotos(photos);
			
			int insert = appClassHygieneDao.insert(appClassHygiene);
			
			List<ClassHygieneItem> hygieneItems = hygieneInfoReq.getClassHygieneItems();
			
			for (ClassHygieneItem hygieneItem : hygieneItems) {
				hygieneItem.setClassHygieneId(appClassHygiene.getId());
				appClassHygieneItemDao.insert(hygieneItem);
			}
			
			return insert;
		}
			// 修改
			String photos = String.join(",", hygieneInfoReq.getPhotos());
			LambdaUpdateWrapper<AppClassHygiene> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(AppClassHygiene::getId, hygieneInfoReq.getId())
					.set(AppClassHygiene::getPhotos, photos)
					.set(AppClassHygiene::getGrade, hygieneInfoReq.getGrade())
					.set(AppClassHygiene::getNotes, hygieneInfoReq.getNotes())
					.set(AppClassHygiene::getModifyTime, new Date());
			boolean update = update(updateWrapper);
			
			for (ClassHygieneItem classHygieneItem : hygieneInfoReq.getClassHygieneItems()) {
				LambdaUpdateWrapper<ClassHygieneItem> itemLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
				itemLambdaUpdateWrapper.eq(ClassHygieneItem::getClassHygieneId, hygieneInfoReq.getId())
						.eq(ClassHygieneItem::getCheckItem, classHygieneItem.getCheckItem())
						.set(ClassHygieneItem::getGrade, classHygieneItem.getGrade());
				appClassHygieneItemDao.update(classHygieneItem, itemLambdaUpdateWrapper);
			}
		
		// 修改
		return update ? 1 : 0;
	}
	
	private List<BClassVo> getBClassVos(Long userId) {
		boolean isDeptManager = false ;
		List<Long> roleIdList = sysUserRoleService.listRoleIdByUserId(userId);
		for (Long roleId : roleIdList) {
			if(roleId == 2 || roleId == 10) {
				isDeptManager = true ;
				break;
			}
		}
		
		List<BClassVo> classList = new ArrayList<>();
		if(isDeptManager) {
			SysUser user = sysUserDao.selectById(userId);
			List<Long> deptIds = sysDeptDao.getAllChildByParent(user.getDeptId());
			classList = bClassDao.getAppClassByDeptIds(deptIds);
		} else {
			// 获取班主任下所有班级
			classList = bClassDao.getAppClassListByTeaId(userId);
		}
		return classList;
	}
}
